package com.haoxuer.discover.weibo.rest.filter;

import com.haoxuer.discover.config.data.entity.User;
import com.haoxuer.discover.filter.common.FilterChain;
import com.haoxuer.discover.filter.common.HandlerRequest;
import com.haoxuer.discover.filter.common.HandlerResponse;
import com.haoxuer.discover.user.service.UserTokenService;
import com.haoxuer.discover.weibo.api.domain.request.FindByIdRequest;
import com.haoxuer.discover.weibo.data.dao.WeiBoDao;
import com.haoxuer.discover.weibo.data.entity.WeiBo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Scope("prototype")
@Component
public class WeiboCheckFilter implements FilterProxy {


  @Autowired
  UserTokenService tokenService;

  @Autowired
  WeiBoDao weiBoDao;

  @Override
  public void doFilter(HandlerRequest handlerRequest, HandlerResponse response, FilterChain filterChain) {
    FindByIdRequest request = (FindByIdRequest) handlerRequest.getAttribute("request");
    Long id = tokenService.user(request.getUserToken());
    if (id == null) {
      response.setCode(502);
      response.setMsg("用户不存在");
      return;
    }
    WeiBo root = weiBoDao.findById(request.getId());
    if (root == null) {
      response.setCode(503);
      response.setMsg("无效id");
      return;
    }
    handlerRequest.setAttribute("root", root);
    handlerRequest.setAttribute("user", User.fromId(id));
    filterChain.doFilter(handlerRequest, response);
  }
}
